--
-- Author: shunguo.chen
-- Date: 2016-11-01 17:33:34
--
-- IMBubbleController
--

local IMBubbleRender = import("..views.renders.IMBubbleRender")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(params)
	self.super.ctor(self, params)

end

function ClassRef:init()
	self._model = app:getInst("IMModel")
end

function ClassRef:listEvent()
    return {
	    "onSpeakInChatroom"
	}
end

function ClassRef:onEvent(eventName, data)
	if eventName == "onSpeakInChatroom" then
		self:speakUpdate(data)
	end
end

function ClassRef:speakUpdate(msg)
	-- dump(msg, "msg")
	-- 简化版屏蔽头顶气泡
	if not EFFECT_ALL_SHOW then return end

	local worldCtl = app:getLaunchCtl()
	if not worldCtl then return end
	if not BattleManager:isBattle() then
		--非战斗
		local my = FieldManager:getMyCharacter()
		if self:canShowBubble(my, msg) then return end

		local teamChas = TeamManager:getTeamCharacters()
		for _,cha in pairs(teamChas) do
			if self:canShowBubble(cha, msg) then return end
		end

		local mapChas = FieldManager:getMapCharacters()
		for _,cha in pairs(mapChas) do
			if self:canShowBubble(cha, msg) then return end
		end
	else
		--战斗中
		if msg.channelId == "team" then
			local teamMembers = BattleManager:getBattleTeamMembers()
			if teamMembers then
				for k,v in pairs(teamMembers) do
					local cha = v
					if self:canShowBubble(cha, msg) then return end
				end
			end
		end
	end
end

function ClassRef:canShowBubble(cha, msg)
	if cha and cha:getUid() == msg:getUid() then
        self:showBubble(cha, msg)
		return true
	end
	return false
end

function ClassRef:showBubble(cha, msg)
	if not cha:isVisible() then return end
	local isBattle = BattleManager:isBattle()
	local render = cha:getIMBubble()
	if nil == render then
		render = IMBubbleRender.create()
		if not isBattle then
			UIHandler:addIMBubble(render)
		end
		cha:setIMBubble(render)
	end

	render:setData(msg)
	render:onBtnClick(function(node)
		local data = node:getData()
		if data and data:getTeamId() then
			app:sendMsg("TeamModel", "reqApplyTeam", data:getTeamId())
		end
	end)

	if not isBattle then
		render:setLocalZOrder(cha:getLocalZOrder())
	end
	cha:showIMBubble(msg:getPpTextXml(), 5)
end

return ClassRef